package com.splic.product.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import com.splic.common.core.DeviceContext;
import com.splic.common.utils.DateUtils;
import com.splic.common.utils.ShiroUtils;
import com.splic.common.utils.StringUtils;
import com.splic.product.cusEnum.FailEnum;
import com.splic.product.domain.*;
import com.splic.product.mapper.UserSubRecordMapper;
import com.splic.product.mapper.VoiceTransferMapper;
import com.splic.product.service.*;
import com.splic.product.util.sign.HttpUtil;
import com.splic.product.util.sign.LfasrSignature;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 转写事件Service业务层处理
 * 
 * @author singe
 * @date 2023-08-17
 */
@CommonsLog
@Service
public class VoiceTransferServiceImpl implements VoiceTransferService
{
    @Autowired
    private VoiceTransferMapper voiceTransferMapper;
    @Autowired
    private UserSubRecordService userSubRecordService;
    @Autowired
    private ProductService productService;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private VoiceProviderService voiceProviderService;

    @Autowired
    private UserService userService;
    @Autowired
    private UserSubRecordMapper userSubRecordMapper;

    /**
     * 查询转写事件
     * 
     * @param id 转写事件主键
     * @return 转写事件
     */
    @Override
    public VoiceTransfer selectVoiceTransferById(Long id)
    {
        return voiceTransferMapper.selectVoiceTransferById(id);
    }

    /**
     * 查询转写事件列表
     * 
     * @param voiceTransfer 转写事件
     * @return 转写事件
     */
    @Override
    public List<VoiceTransfer> selectPageList(VoiceTransfer voiceTransfer)
    {
        return voiceTransferMapper.selectVoiceTransferList(voiceTransfer);
    }

    /**
     * 查询转写事件列表
     *
     * @param voiceTransfer 转写事件
     * @return 转写事件
     */
    @Override
    public List<VoiceTransfer> selectVoiceTransferList(VoiceTransfer voiceTransfer)
    {
        if (StringUtils.isEmpty(voiceTransfer.getStartCreateTime())) {
            voiceTransfer.setStartCreateTime(DateUtil.formatDate(DateUtil.offsetDay(new Date(), -7)));
        }
        if (StringUtils.isEmpty(voiceTransfer.getEndCreateTime())) {
            voiceTransfer.setEndCreateTime(DateUtil.formatDate(DateUtil.offsetDay(new Date(), 1)));
        } else {
            voiceTransfer.setEndCreateTime(DateUtil.formatDate(DateUtil.offsetDay(DateUtils.parseDate(voiceTransfer.getEndCreateTime()), 1)));
        }
        return voiceTransferMapper.selectVoiceTransferList(voiceTransfer);
    }

    /**
     * 新增转写事件
     * 
     * @param voiceTransfer 转写事件
     * @return 结果
     */
    @Override
    public int insert(VoiceTransfer voiceTransfer)
    {
        voiceTransfer.setCreateTime(DateUtils.getNowDate());
        return voiceTransferMapper.insert(voiceTransfer);
    }

    /**
     * 修改转写事件
     * 
     * @param voiceTransfer 转写事件
     * @return 结果
     */
    @Override
    public int update(VoiceTransfer voiceTransfer)
    {
        voiceTransfer.setUpdateTime(DateUtils.getNowDate());
        return voiceTransferMapper.update(voiceTransfer);
    }


    /**
     * 删除转写事件信息
     * 
     * @param id 转写事件主键
     * @return 结果
     */
    @Override
    public int deleteById(Long id)
    {
        return voiceTransferMapper.deleteById(id);
    }
    /**
     * 修改转写事件
     *
     * @param voiceTransfer 转写事件信息
     * @return 结果
     */
    @Override
    @Transactional
    public int saveOrUpdate(VoiceTransfer voiceTransfer)
    {
        if(voiceTransfer.getId() != null){
            voiceTransfer.setUpdateTime(new Date());
            return voiceTransferMapper.update(voiceTransfer);
        }else{
            voiceTransfer.setCreateTime(new Date());
            return voiceTransferMapper.insert(voiceTransfer);
        }
    }

    @Override
    public VoiceTransfer judgeTransfer(VoiceTransfer transferReq) {
        VoiceTransfer transfer = new VoiceTransfer();

        Long userId = ShiroUtils.getUserId();
        User user = userService.selectUserById(userId);
        if (user == null) {
            transfer.setReturnCode(-1);
            transfer.setReturnMsg("用户不存在");
            return transfer;
        }
        String deviceId = DeviceContext.getDeviceIdentify();
        String packageKey = DeviceContext.getProductPackageKey();
        Product product = productService.getByPackageKey(packageKey);
        GoodsType goodsType = goodsTypeService.selectGoodsTypeById(transferReq.getGoodsTypeId());

        UserSubRecord record = new UserSubRecord();
        record.setUserId(userId);
        record.setProductId(product.getId());
        record.setGoodsTypeId(goodsType.getId());
        record.setStatus(1);
        record.setIsDelete(0);
        List<UserSubRecord> records = userSubRecordService.selectUserSubRecordList(record);

        if (records != null && records.size() > 0) {
            UserSubRecord origin = records.get(0);
            if (origin.getEffictTransferTime() != null && origin.getEffictTransferTime() > 0) {
                List<VoiceProvider> providers = voiceProviderService.selectEffictList();
                if (providers != null && providers.size() > 0) {
                    VoiceProvider provider = null;
                    // 只有一个服务商
                    if (providers.size() == 1) {
                        // 请求使用iflytek
                        if (transferReq.getSupportStt() == null || transferReq.getSupportStt().equals("iflytek")) {
                            if (providers.get(0).getVoiceName().equals("iflytek")) {
                                provider = providers.get(0);
                            }
                            // 请求使用iflytek+deepgram
                        } else if (transferReq.getSupportStt().equals("iflytek+deepgram")) {
                            provider = providers.get(0);
                            // 请求使用deepgram
                        } else if (transferReq.getSupportStt().equals("deepgram")) {
                            if (providers.get(0).getVoiceName().equals("deepgram")) {
                                provider = providers.get(0);
                            }
                        }
                    } else {
                        // 多个服务商
                        // 请求使用iflytek
                        if (transferReq.getSupportStt() == null || transferReq.getSupportStt().equals("iflytek")) {
                            for (VoiceProvider pro : providers) {
                                if (pro.getVoiceName().equals("iflytek")) {
                                    provider = pro;
                                    break;
                                }
                            }
                            // 请求使用iflytek+deepgram
                        } else if (transferReq.getSupportStt().equals("iflytek+deepgram")) {
                            provider = selectByInternalProbability(providers);
                            // 请求使用deepgram
                        } else if (transferReq.getSupportStt().equals("deepgram")) {
                            for (VoiceProvider pro : providers) {
                                if (pro.getVoiceName().equals("deepgram")) {
                                    provider = pro;
                                    break;
                                }
                            }
                        }
                    }
                    // 服务商不匹配
                    if (provider == null) {
                        transfer.setReturnCode(-1);
                        transfer.setReturnMsg("不支持的转写方式");
                        return transfer;
                    }
//                    for (VoiceProvider provider : providers) {
                        List<String> langList = Arrays.stream(provider.getVoiceLanguages().split(",")).filter(e -> e.equals(transferReq.getLanguage())).collect(Collectors.toList());
                        if (langList.size() > 0) {
                            List<String> formatList = Arrays.stream(provider.getVoiceFormat().split(",")).filter(e -> e.equals(transferReq.getVoiceFormat())).collect(Collectors.toList());
                            if (formatList.size() > 0) {
                                if (transferReq.getVoiceSize() < provider.getVoiceSize() * 1000) {
                                    if (transferReq.getVoiceDuration() < provider.getVoiceDuration() * 3600000) {
                                        List<String> samplingList = Arrays.stream(provider.getVoiceSampling().split(",")).filter(e -> e.equals(transferReq.getVoiceSampling())).collect(Collectors.toList());
                                        if (samplingList.size() > 0) {
                                            List<String> bitList = Arrays.stream(provider.getVoiceBit().split(",")).filter(e -> e.equals(transferReq.getVoiceBit())).collect(Collectors.toList());
                                            if (bitList.size() > 0) {
                                                Long time = voiceTransferMapper.getAllUnfinished(user.getUserIdentify(), product.getId());
                                                if (time == null) {
                                                    time = 0L;
                                                }
                                                if (time + transferReq.getVoiceDuration() <= origin.getEffictTransferTime()) {
                                                    if (provider.getVoiceName().equals("iflytek")) {
                                                        transfer.setTransferId("xf" + System.currentTimeMillis());
                                                        transfer.setTransferAppId(product.getXfAppId());
//                                                        transfer.setAppKey(product.getXfAppKey());
                                                        transfer.setTransferAppSecret(product.getXfAppSecret());
                                                        LfasrSignature lfasrSignature = new LfasrSignature(product.getXfAppId(), product.getXfAppSecret());
                                                        try{
                                                            transfer.setSign(lfasrSignature.getSigna());
                                                            transfer.setTimestamp(lfasrSignature.getTs());
                                                        } catch (Exception e) {
                                                            e.printStackTrace();
                                                            transfer.setReturnCode(-1);
                                                            transfer.setReturnMsg("加密失败");
                                                            return transfer;
                                                        }
                                                    } else if (provider.getVoiceName().equals("deepgram")) {
                                                        transfer.setTransferId("dg" + System.currentTimeMillis());
                                                    } else if (provider.getVoiceName().equals("baidu")) {
                                                        transfer.setTransferId("bd" + System.currentTimeMillis());
                                                        transfer.setTransferAppId(product.getBdAppId());
//                                                        transfer.setAppKey(product.getBdAppKey());
                                                        transfer.setTransferAppSecret(product.getBdAppSecret());
                                                    } else {
                                                        transfer.setTransferId("xf" + System.currentTimeMillis());
                                                        transfer.setTransferAppId(product.getXfAppId());
//                                                        transfer.setAppKey(product.getXfAppKey());
                                                        transfer.setTransferAppSecret(product.getXfAppSecret());
                                                        LfasrSignature lfasrSignature = new LfasrSignature(product.getXfAppId(), product.getXfAppSecret());
                                                        try{
                                                            transfer.setSign(lfasrSignature.getSigna());
                                                        } catch (Exception e) {
                                                            e.printStackTrace();
                                                            transfer.setReturnCode(-1);
                                                            transfer.setReturnMsg("加密失败");
                                                            return transfer;
                                                        }
                                                    }
                                                    transfer.setCompany(provider.getId());
                                                    transfer.setCompanyName(provider.getVoiceName());
                                                    transfer.setProductId(product.getId());
                                                    transfer.setGoodsTypeId(goodsType.getId());
                                                    transfer.setProductName(product.getName());
                                                    transfer.setUserId(user.getUserIdentify());
                                                    transfer.setDeviceId(deviceId);
                                                    transfer.setTransferLanguages(transferReq.getLanguage());
                                                    transfer.setTransferName(transferReq.getName());
                                                    transfer.setTransferFormat(transferReq.getVoiceFormat());
                                                    transfer.setTransferSize(transferReq.getVoiceSize());
                                                    transfer.setTransferPath(transferReq.getPath());
                                                    transfer.setTransferDuration(transferReq.getVoiceDuration());
                                                    transfer.setTransferSampling(transferReq.getVoiceSampling());
                                                    transfer.setTransferBit(transferReq.getVoiceBit());
                                                    transfer.setStatus(0);
                                                    transfer.setTransferApi(provider.getVoiceUrl());
                                                    transfer.setTransferResApi(provider.getVoiceResUrl());
                                                    transfer.setCreateTime(new Date());
                                                    voiceTransferMapper.insert(transfer);
                                                    transfer.setReturnCode(1);
                                                    return transfer;
                                                } else {
                                                    transfer.setReturnCode(-1);
                                                    transfer.setReturnMsg(String.format("您的%s服务余额不足，请您订阅获取更多余额",goodsType.getName()));
                                                    return transfer;
                                                }
                                            } else {
                                                transfer.setReturnCode(-1);
                                                transfer.setReturnMsg("不支持的比特率");
                                                return transfer;
                                            }
                                        } else {
                                            transfer.setReturnCode(-1);
                                            transfer.setReturnMsg("不支持的采样率");
                                            return transfer;
                                        }
                                    } else {
                                        transfer.setReturnCode(-1);
                                        transfer.setReturnMsg("音频时长超限");
                                        return transfer;
                                    }
                                } else {
                                    transfer.setReturnCode(-1);
                                    transfer.setReturnMsg("文件大小超限");
                                    return transfer;
                                }
                            } else {
                                transfer.setReturnCode(-1);
                                transfer.setReturnMsg("不支持的文件格式");
                                return transfer;
                            }
                        } else {
                            transfer.setReturnCode(-1);
                            transfer.setReturnMsg("不支持的语种");
                            return transfer;
                        }
//                    }
//                    transfer.setReturnCode(-1);
//                    transfer.setReturnMsg("暂无可用服务");
//                    return transfer;
                } else {
                    transfer.setReturnCode(-1);
                    transfer.setReturnMsg("暂无可用服务");
                    return transfer;
                }
            } else {
                transfer.setReturnCode(-1);
                transfer.setReturnMsg(String.format("您的%s服务余额已用完，请您订阅获取更多余额",goodsType.getName()));
                return transfer;
            }
        } else {
            transfer.setReturnCode(-1);
            transfer.setReturnMsg(String.format("请您先订阅%s服务",goodsType.getName()));
            return transfer;
        }
    }

    /**
     * 根据元素内含的概率属性选择列表中的一个元素。
     *
     * @param elements 具有概率属性的元素列表
     * @return 随机选择的元素
     */
    public static VoiceProvider selectByInternalProbability(List<VoiceProvider> elements) {
        double totalWeight = elements.stream().mapToDouble(VoiceProvider::getVoiceUse).sum();
        Random random = new Random();
        double randomValue = random.nextDouble() * totalWeight;
        double cumulativeWeight = 0;

        for (VoiceProvider element : elements) {
            cumulativeWeight += element.getVoiceUse();
            if (randomValue <= cumulativeWeight) {
                return element;
            }
        }
        log.error("The sum of probabilities does not equal to 1 or there's an error in the process.");
        return elements.get(0);
    }

    @Override
    public Integer updateTransfer(VoiceTransfer transferReq) {
        VoiceTransfer transfer = voiceTransferMapper.selectVoiceTransferByTransferId(transferReq.getTransferId());
        if (transfer != null) {
            VoiceTransfer temp = new VoiceTransfer();
            temp.setId(transfer.getId());
            if ("-1".equals(transferReq.getProviderId())) {
                temp.setStatus(3);
                temp.setResultCode("-1");
                temp.setResultTime(new Date());
                temp.setFailReason(FailEnum.getDesByCode(-1));
                int result = voiceTransferMapper.update(temp);
//                if (result == 1) {
//                    VoiceTransfer saveTemp = new VoiceTransfer();
//                    saveTemp.setTransferId(transfer.getTransferId());
//                    saveTemp.setProviderId(transfer.getProviderId());
//                    saveTemp.setResultCode("-1");
//                    saveTemp.setResultTime(new Date());
//                    saveTemp.setFailReason(FailEnum.getDesByCode(-1));
//                    saveTemp(saveTemp);
//                }
                return result;
            } else {
                temp.setStatus(2);
                temp.setStartTime(new Date());
                temp.setProviderId(transferReq.getProviderId());
                temp.setEstimatedTime(transferReq.getEstimatedTime());
                return voiceTransferMapper.update(temp);
            }
        }
        return 0;
    }

    @Override
    public void callbackTransfer(String orderId, String status) {
        VoiceTransfer transfer = voiceTransferMapper.selectVoiceTransferByProviderId(orderId);
        if (transfer == null) {
            if ("1".equals(status)) {
                String packageKey = DeviceContext.getProductPackageKey();
                Product product = productService.getByPackageKey(packageKey);
                transfer = new VoiceTransfer();
                transfer.setProviderId(orderId);
                transfer.setTransferAppId(product.getXfAppId());
                transfer.setTransferAppSecret(product.getXfAppSecret());
                getResult(transfer);
            } else {
                VoiceTransfer saveTemp = new VoiceTransfer();
                saveTemp.setProviderId(orderId);
                saveTemp.setResultTime(new Date());
                saveTemp.setFailReason("讯飞转写失败回调通知");
                saveTemp(saveTemp);
            }
        } else {
            VoiceTransfer temp = new VoiceTransfer();
            temp.setId(transfer.getId());
            if ("1".equals(status)) {
                temp.setStatus(4);
                voiceTransferMapper.update(temp);
                transfer.setProviderId(orderId);
            } else {
                temp.setStatus(3);
                voiceTransferMapper.update(temp);
            }
            getResult(transfer);
        }
    }

//    public static void main(String[] args) throws Exception {
//        VoiceTransfer transfer = new VoiceTransfer();
//        transfer.setId(610L);
//        transfer.setProviderId("DKHJQ20240801164451655XiY3ic3PzbfaLoAB");
//        transfer.setTransferAppId("d4e01fad");
//        transfer.setTransferAppSecret("52ad4b11b5dbdbc5c3b597a9b8fd914f");
//        getResult(transfer);
//    }
    @Override
    public void transferCallbackTask() {
        VoiceTransfer temp = new VoiceTransfer();
        temp.setStatus(2);
        temp.setStartCreateTime(DateUtil.formatDate(DateUtil.offsetDay(new Date(), -7)));
        temp.setEndCreateTime(DateUtil.formatDate(DateUtil.offsetDay(new Date(), 1)));
        log.info("时间间隔：" + temp.getStartCreateTime() + "至" + temp.getEndCreateTime());
        List<VoiceTransfer> transferList = voiceTransferMapper.selectVoiceTransferList(temp);
        log.info("转写中：" + (transferList != null ? transferList.size() : 0));
        temp.setStatus(4);
        List<VoiceTransfer> transferList4 = voiceTransferMapper.selectVoiceTransferList(temp);
        log.info("获得完成回调：" + (transferList4 != null ? transferList4.size() : 0));
        if (transferList4 != null && transferList4.size() > 0){
            transferList.addAll(transferList4);
        }
        for (VoiceTransfer transfer : transferList) {
            log.info("开始获取结果：" + transfer.getTransferId());
            if (transfer.getCompanyName() != null && transfer.getCompanyName().equals("deepgram")) {
                continue;
            }
            VoiceProvider voiceProvider = voiceProviderService.selectVoiceProviderById(transfer.getCompany());
            try {
                long diff = System.currentTimeMillis() - transfer.getStartTime().getTime();
                log.info("开始时间：" + transfer.getStartTime() + "，耗时：" + diff + "，预计时间：" + transfer.getEstimatedTime());
                if (diff > transfer.getEstimatedTime() * 0.8) {
                    if (diff > voiceProvider.getTimeout() * 1000) {
                        VoiceTransfer tempV = new VoiceTransfer();
                        tempV.setId(transfer.getId());
                        tempV.setStatus(3);
                        tempV.setFailReason("转写超时");
                        voiceTransferMapper.update(tempV);
                        continue;
                    }
                    log.info("开始获取结果");
                    getResult(transfer);
                }
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void callbackDeepgram(JSONObject response) {
        log.info(JSONUtil.toJsonStr(response));
        String providerId = response.getJSONObject("metadata").getStr("request_id");
        VoiceTransfer transfer = voiceTransferMapper.selectVoiceTransferByProviderId(providerId);
        log.info(transfer);
        VoiceTransfer saveTemp = new VoiceTransfer();
        if (transfer != null) {
            saveTemp.setTransferId(transfer.getTransferId());
        }
        saveTemp.setProviderId(providerId);
        saveTemp.setResultCode("4");
        saveTemp.setResultTime(new Date());
        saveTemp.setResultContent(JSONUtil.toJsonStr(response.getJSONObject("results")));
        saveTemp.setRealDuration((int) (Math.ceil(response.getJSONObject("metadata").getDouble("duration")) * 1000));
        saveTemp(saveTemp);
        if (transfer != null) {
            User user = userService.getByUserIdentify(transfer.getUserId());
            UserSubRecord record = userSubRecordMapper.selectLastTime(user.getId(), transfer.getProductId(), transfer.getGoodsTypeId());
            record.setEffictTransferTime(record.getEffictTransferTime() - saveTemp.getRealDuration());
            userSubRecordMapper.update(record);
            VoiceTransfer updateTemp = new VoiceTransfer();
            updateTemp.setId(transfer.getId());
            updateTemp.setStatus(5);
            voiceTransferMapper.update(updateTemp);
        }
    }

    private static final String HOST = "https://raasr.xfyun.cn";
//    private static final String appid = "5b307eb3";
//    private static final String keySecret = "38c8f763b9dce84cce98b3d7208da7e9";

    public void getResult(VoiceTransfer transfer) {
        try {
            Gson gson = new Gson();
            HashMap<String, Object> map = new HashMap<>(16);
            map.put("orderId", transfer.getProviderId());
            LfasrSignature lfasrSignature = new LfasrSignature(transfer.getTransferAppId(), transfer.getTransferAppSecret());
            map.put("signa", lfasrSignature.getSigna());
            map.put("ts", lfasrSignature.getTs());
            map.put("appId", transfer.getTransferAppId());
            map.put("resultType", "transfer");
            String paramString = HttpUtil.parseMapToPathParam(map);
            String url = HOST + "/v2/api/getResult" + "?" + paramString;
            log.info("\nget_result_url:" + url);
            String response = HttpUtil.iflyrecGet(url);
            if (StringUtils.isEmpty(response)) {
                log.info("请求结果返回为空:" + response);
            }
            JsonParse jsonParse = gson.fromJson(response, JsonParse.class);
            log.info("订单完成:" + response);
            if (transfer.getId() == null) {
                if (jsonParse.content.orderInfo.status == 4) {
                    VoiceTransfer temp = new VoiceTransfer();
                    temp.setTransferId(transfer.getTransferId());
                    temp.setProviderId(transfer.getProviderId());
                    temp.setResultCode(String.valueOf(jsonParse.content.orderInfo.status));
                    temp.setResultContent(jsonParse.content.orderResult);
                    temp.setResultTime(new Date());
                    temp.setRealDuration(jsonParse.content.orderInfo.realDuration);
                    temp.setOriginDuration(jsonParse.content.orderInfo.originalDuration);
                    temp.setFailReason("");
                    saveTemp(temp);
                } else if (jsonParse.content.orderInfo.status == -1) {
                    VoiceTransfer saveTemp = new VoiceTransfer();
                    saveTemp.setTransferId(transfer.getTransferId());
                    saveTemp.setProviderId(transfer.getProviderId());
                    saveTemp.setResultCode(String.valueOf(jsonParse.content.orderInfo.status));
                    saveTemp.setResultTime(new Date());
                    saveTemp.setFailReason(FailEnum.getDesByCode(jsonParse.content.orderInfo.failType));
                    saveTemp(saveTemp);
                }
            } else {
                if (jsonParse.content.orderInfo.status == 4) {
                    VoiceTransfer saveTemp = new VoiceTransfer();
                    saveTemp.setTransferId(transfer.getTransferId());
                    saveTemp.setProviderId(transfer.getProviderId());
                    saveTemp.setResultCode(String.valueOf(jsonParse.content.orderInfo.status));
                    saveTemp.setResultContent(jsonParse.content.orderResult);
                    saveTemp.setResultTime(new Date());
                    saveTemp.setRealDuration(jsonParse.content.orderInfo.realDuration);
                    saveTemp.setOriginDuration(jsonParse.content.orderInfo.originalDuration);
                    saveTemp.setFailReason("");
                    saveTemp(saveTemp);

                    VoiceTransfer updateTemp = new VoiceTransfer();
                    updateTemp.setId(transfer.getId());
                    updateTemp.setStatus(5);
                    voiceTransferMapper.update(updateTemp);

                    User user = userService.getByUserIdentify(transfer.getUserId());
                    UserSubRecord record = userSubRecordMapper.selectLastTime(user.getId(), transfer.getProductId(), transfer.getGoodsTypeId());
                    record.setEffictTransferTime(record.getEffictTransferTime() - jsonParse.content.orderInfo.realDuration);
                    userSubRecordMapper.update(record);
                } else if (jsonParse.content.orderInfo.status == -1) {
                    VoiceTransfer saveTemp = new VoiceTransfer();
                    saveTemp.setTransferId(transfer.getTransferId());
                    saveTemp.setProviderId(transfer.getProviderId());
                    saveTemp.setResultCode(String.valueOf(jsonParse.content.orderInfo.status));
                    saveTemp.setResultTime(new Date());
                    saveTemp.setFailReason(FailEnum.getDesByCode(jsonParse.content.orderInfo.failType));
                    saveTemp(saveTemp);
                    VoiceTransfer updateTemp = new VoiceTransfer();
                    updateTemp.setId(transfer.getId());
                    updateTemp.setStatus(3);
                    voiceTransferMapper.update(updateTemp);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<VoiceTransfer> searchUserList() {
        Long userId = ShiroUtils.getUserId();
        User user = userService.selectUserById(userId);
        VoiceTransfer transfer = new VoiceTransfer();
        transfer.setUserId(user.getUserIdentify());
        return voiceTransferMapper.selectVoiceTransferList(transfer);
    }

    @Override
    public VoiceTransfer apiVoiceTransferById(String transferId) {
        VoiceTransfer transfer = voiceTransferMapper.selectVoiceTransferByTransferId(transferId);
        VoiceProvider voiceProvider = voiceProviderService.selectVoiceProviderById(transfer.getCompany());
        if (voiceProvider.getVoiceName().equals("iflytek")) {
            if (transfer.getStatus() == 5) {
                if (!"5".equals(transfer.getResultCode())) {
                    voiceTransferMapper.updateResult(transfer.getProviderId(), "5");
                }
            } else if (transfer.getStatus() == 4) {
                try {
                    getResult(transfer);
                    transfer = voiceTransferMapper.selectVoiceTransferByTransferId(transferId);
                    if (transfer.getStatus() == 5) {
                        voiceTransferMapper.updateResult(transfer.getProviderId(), "5");
                    } else if (transfer.getStatus() == 3) {
                        voiceTransferMapper.updateResult(transfer.getProviderId(), "6");
                    }
                } catch (Exception e){
                    e.printStackTrace();
                }
            } else if (transfer.getStatus() == 3) {
                if (!"6".equals(transfer.getResultCode())) {
                    voiceTransferMapper.updateResult(transfer.getProviderId(), "6");
                }
            } else if (transfer.getStatus() == 2) {
                if (System.currentTimeMillis() - transfer.getStartTime().getTime() > transfer.getEstimatedTime() * 0.8) {
                    try {
                        if (System.currentTimeMillis() - transfer.getStartTime().getTime() > voiceProvider.getTimeout() * 1000) {
                            VoiceTransfer tempV = new VoiceTransfer();
                            tempV.setId(transfer.getId());
                            tempV.setStatus(3);
                            tempV.setFailReason("转写超时");
                            voiceTransferMapper.update(tempV);
                            return voiceTransferMapper.selectVoiceTransferByTransferId(transferId);
                        }
                        getResult(transfer);
                        transfer = voiceTransferMapper.selectVoiceTransferByTransferId(transferId);
                        if (transfer.getStatus() == 5) {
                            voiceTransferMapper.updateResult(transfer.getProviderId(), "5");
                        } else if (transfer.getStatus() == 3) {
                            voiceTransferMapper.updateResult(transfer.getProviderId(), "6");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if (voiceProvider.getVoiceName().equals("deepgram")) {
            if (transfer.getStatus() == 5) {
                voiceTransferMapper.updateResult(transfer.getProviderId(), "5");
            } else if (transfer.getStatus() == 2) {
                if ("4".equals(transfer.getResultCode())) {
                    User user = userService.getByUserIdentify(transfer.getUserId());
                    UserSubRecord record = userSubRecordMapper.selectLastTime(user.getId(), transfer.getProductId(), transfer.getGoodsTypeId());
                    record.setEffictTransferTime(record.getEffictTransferTime() - transfer.getRealDuration());
                    userSubRecordMapper.update(record);
                    VoiceTransfer updateTemp = new VoiceTransfer();
                    updateTemp.setId(transfer.getId());
                    updateTemp.setStatus(5);
                    voiceTransferMapper.update(updateTemp);
                    return voiceTransferMapper.selectVoiceTransferByTransferId(transferId);
                } else {
                    try {
                        if (System.currentTimeMillis() - transfer.getStartTime().getTime() > voiceProvider.getTimeout() * 1000) {
                            VoiceTransfer saveTemp = new VoiceTransfer();
                            saveTemp.setTransferId(transfer.getTransferId());
                            saveTemp.setProviderId(transfer.getProviderId());
                            saveTemp.setReturnCode(6);
                            saveTemp.setResultTime(new Date());
                            saveTemp.setFailReason("转写超时");
                            saveTemp(saveTemp);

                            VoiceTransfer tempV = new VoiceTransfer();
                            tempV.setId(transfer.getId());
                            tempV.setStatus(3);
                            voiceTransferMapper.update(tempV);
                            return voiceTransferMapper.selectVoiceTransferByTransferId(transferId);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        if (transfer.getStatus() == 4) {
            transfer.setStatus(2);
        }
        return transfer;
    }

    public void saveTemp(VoiceTransfer saveTemp){
        //根据providerId查询
        VoiceTransfer origin = voiceTransferMapper.selectVoiceResultByProviderId(saveTemp.getProviderId());
        //双重检查锁
        if (origin == null) {
            synchronized (this) {
                origin = voiceTransferMapper.selectVoiceResultByProviderId(saveTemp.getProviderId());
                if (origin == null) {
                    voiceTransferMapper.saveVoiceResult(saveTemp);
                } else {
                    saveTemp.setId(origin.getId());
                    voiceTransferMapper.updateVoiceResult(saveTemp);
                }
            }
        }
    }

    public static void write(String resp) throws IOException {
        //将写入转化为流的形式
        BufferedWriter bw = new BufferedWriter(new FileWriter("src\\main\\resources\\output\\test.txt"));
        String ss = resp;
        bw.write(ss);
        //关闭流
        bw.close();
        System.out.println("写入txt成功");
    }

    class JsonParse {
        Content content;
    }

    class Content {
        OrderInfo orderInfo;
        String orderResult;
    }

    class OrderInfo {
        Integer status;
        Integer failType;
        Integer realDuration;
        Integer originalDuration;
    }
}
